package dep

import (
	"context"
	"runtime"

	"gitee.com/go-errors/errors"
	"gitee.com/go-wena/wena/utils/archive"
	"gitee.com/go-wena/wena/utils/httpx"
)

const baseURL = "https://golang.google.cn/dl/"

func DownloadNewestGo(ctx context.Context, saveTo string, progress ...httpx.ProgressFunc) error {
	version, err := GetNewestGoVersion(ctx)
	if err != nil {
		return err
	}

	extract := archive.New().DirectKind(version.Filename).TrimRootPath().SaveTo(saveTo).WriteTo()
	process := httpx.ProcessProgress(extract, progress...)
	return httpx.Get(baseURL + version.Filename).Process(process).Debug().Exec(ctx)
}

func GetNewestGoVersion(ctx context.Context) (*GoFile, error) {
	var versions []*struct {
		Files []*GoFile `json:"files"`
	}

	if err := httpx.Get(baseURL + "?mode=json").Process(httpx.ProcessJSON(&versions)).Exec(ctx); err != nil {
		return nil, err
	}

	for _, ver := range versions {
		for _, goFile := range ver.Files {
			if goFile.Kind == "archive" && goFile.Os == runtime.GOOS && goFile.Arch == runtime.GOARCH {
				return goFile, nil
			}
		}
	}

	return nil, errors.Errorf("platform: %s, %s, kind: archive not found", runtime.GOOS, runtime.GOARCH)
}

type GoFile struct {
	Filename string `json:"filename"`
	Os       string `json:"os"`
	Arch     string `json:"arch"`
	Version  string `json:"version"`
	Sha256   string `json:"sha256"`
	Size     int64  `json:"size"`
	Kind     string `json:"kind"`
}
